package cn.learn.office.excel_v3;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author huangyezhan
 * @version 1.0
 * @date 2021年06月11日16:32
 */
@Slf4j
public class ConvertFieldName {

    public static <T> String convertToFieldName(IGetter<T> fn) {
        SerializedLambda lambda = getSerializedLambda(fn);
        Assert.notNull(lambda, "核实该属性，是否存在！");
        String methodName = lambda.getImplMethodName();
        String prefix     = null;
        if (methodName.startsWith("get")) {
            prefix = "get";
        } else if (methodName.startsWith("is")) {
            prefix = "is";
        }
        if (prefix == null) {
            prefix = "";
            log.warn("该getter属性[{}]定义与众不同！", methodName);
        }
        return toLowerCaseFirstOne(methodName.replace(prefix, ""));
    }

    public static SerializedLambda getSerializedLambda(Serializable fn) {
        try {
            // 编译的时候，会自动生成writeReplace这个方法
            Method method = fn.getClass().getDeclaredMethod("writeReplace");
            method.setAccessible(Boolean.TRUE);
            return (SerializedLambda) method.invoke(fn);
        } catch (NoSuchMethodException e) {
            log.error("Excel工具类，不存在该方法：{}", e.getMessage());
        } catch (IllegalAccessException e) {
            log.error("Excel工具类，非法参数：{}", e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("Excel工具类，方法调用异常：{}", e.getMessage());
        }
        return null;
    }

    public static String toLowerCaseFirstOne(String field) {
        if (Character.isLowerCase(field.charAt(0))) {
            return field;
        } else {
            char   firstOne = Character.toLowerCase(field.charAt(0));
            String other    = field.substring(1);
            return firstOne + other;
        }
    }

}
